package com.webchat.pgc.messagequeue.local;

import com.webchat.common.service.messagequeue.local.AbstractArrayBlockQueue;
import com.webchat.common.service.messagequeue.task.MessageQueueTaskDTO;
import com.webchat.domain.dto.queue.MallProductStockUpdateMessageDTO;
import com.webchat.pgc.messagequeue.task.PgcMessageQueueTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;


/**
 * 用于电商库存数据库更新任务入分布式队列失败时，我们走本地队列写失败队列任务表
 */
@Service
public class MQTaskWriteDataBaseQueue extends AbstractArrayBlockQueue<MessageQueueTaskDTO> {

    @Autowired
    private PgcMessageQueueTaskService messageQueueTaskService;

    /**
     * 队列长度
     */
    private static final int QUEUE_CAPACITY = 5000;

    private static ArrayBlockingQueue<MessageQueueTaskDTO> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);

    @Override
    protected ArrayBlockingQueue<MessageQueueTaskDTO> queue() {
        return queue;
    }

    @Override
    protected boolean consume(MessageQueueTaskDTO message) {
        messageQueueTaskService.saveFailTask2DB(message);
        return true;
    }

    /**
     * 拒绝策略：直接当当前主线程去写库
     *
     * PS：doReject的写库跟前面consume写库实现逻辑逻辑一直的
     * 区别在与doReject是在当前主线程执行，而consume是在本地队列consume线程中执行
     *
     * @param messages
     * @return
     */
    @Override
    public boolean doReject(List<MessageQueueTaskDTO> messages) {
        messageQueueTaskService.saveFailTask2DB(messages);
        return true;
    }
}
